Skip to content

Latest commit

 

History

History
273 lines (217 loc) · 8.93 KB

12.Exporting multiple formats in NETCore via request headers.md

File metadata and controls

273 lines (217 loc) · 8.93 KB

Exporting multiple formats in NETCore via request headers

Main steps

1. Installation package

Install-Package Magicodes.IE.AspNetCore

2. Start configuration

In the Configure() method of Startup.cs , after the UseRouting() middleware, register the following middleware

public void Configure(IApplicationBuilder app)
{
    app.UseRouting();
    app.UseMagiCodesIE();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

The above can provide us with export services in the form of middleware, so let's look at another way as follows.

  public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers(options=>options.Filters.Add(typeof(MagicodesFilter)));
            }

Both of the above can provide us with export services, we just need to configure the controller with the required features. The characteristics mainly do a role of identification, some relevant content data, while the identification can be exported as a file.

[HttpGet("excel")]
[Magicodes(Type = typeof(ExportTestDataWithAttrs))]
public List<ExportTestDataWithAttrs> Excel()
{
    return GenFu.GenFu.ListOf<ExportTestDataWithAttrs>(100);
}

In the above code snippet we identify that the class is allowed to be exported. Also we need to specify the type of our exported class by Type.

Once this is filled in we can pass the call to the address, but note that we must add a request header to identify the type of file being exported. If we don't add a request header, then the data returned here will still be in json format. The request header name is Magicodes-Type.

       /// <summary>
        ///     XLSX
        /// </summary>
        internal const string XLSXHttpContentMediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        /// <summary>
        ///     PDF
        /// </summary>
        internal const string PDFHttpContentMediaType = "application/pdf";
        /// <summary>
        ///     DOCX
        /// </summary>
        internal const string DOCXHttpContentMediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        /// <summary>
        ///     HTML
        /// </summary>
        internal const string HTMLHttpContentMediaType = "text/html";

If we say that it is a template export word or pdf or even say html file then we do the same as shown below.

[HttpGet("Word")]
        [Magicodes(Type = typeof(ReceiptInfo), TemplatePath = ".//ExportTemplates//receipt.cshtml")]
        public ReceiptInfo Word()
        {
            return new ReceiptInfo
            {
                Amount = 22939.43M,
                Grade = "2019秋",
                IdNo = "43062619890622xxxx",
                Name = "张三",
                Payee = "湖南心莱信息科技有限公司",
                PaymentMethod = "微信支付",
                Profession = "运动训练",
                Remark = "学费",
                TradeStatus = "已完成",
                TradeTime = DateTime.Now,
                UppercaseAmount = "贰万贰仟玖佰叁拾玖圆肆角叁分",
                Code = "19071800001"
            };
        }

We still need to specify the Type and then specify the template address via TemplatePath

Similarly we can also use the request header to identify whether the request is a file format export or not.

        [HttpGet("pdf")]
        [Magicodes(Type = typeof(BatchPortraitReceiptInfoInput), TemplatePath = ".//ExportTemplates//batchReceipt.cshtml")]
        public BatchPortraitReceiptInfoInput Pdf()
        {

            var input = new BatchPortraitReceiptInfoInput
            {
                Payee = "湖南心莱信息科技有限公司",
                SealUrl =
                @"data:image/jpeg;base64....",
                LogoUrl =
                @"data:image/png;base64....",
                ReceiptInfoInputs = new List<BatchPortraitReceiptInfoDto>()
            };

            for (var i = 0; i < 500; i++)
                input.ReceiptInfoInputs.Add(new BatchPortraitReceiptInfoDto
                {
                    Amount = 22939.43M,
                    Grade = "2019秋",
                    IdNo = "43062619890622xxxx",
                    Name = "张三",
                    PaymentMethod = "微信支付",
                    Profession = "运动训练",
                    Remark = "学费",
                    TradeStatus = "已完成",
                    TradeTime = DateTime.Now,
                    UppercaseAmount = "贰万贰仟玖佰叁拾玖圆肆角叁分",
                    Code = "1907180000" + i
                });
            return input;
        }


        [HttpGet("Html")]
        [Magicodes(Type = typeof(ReceiptInfo), TemplatePath = ".//ExportTemplates//receipt.cshtml")]
        public ReceiptInfo Html()
        {
            return new ReceiptInfo
            {
                Amount = 22939.43M,
                Grade = "2019秋",
                IdNo = "43062619890622xxxx",
                Name = "张三",
                Payee = "湖南心莱信息科技有限公司",
                PaymentMethod = "微信支付",
                Profession = "运动训练",
                Remark = "学费",
                TradeStatus = "已完成",
                TradeTime = DateTime.Now,
                UppercaseAmount = "贰万贰仟玖佰叁拾玖圆肆角叁分",
                Code = "19071800001"
            };
        }

Swagger中使用

By inheriting the IOperationFilter interface, create the AddRequiredHeaderParameter class, add a header type parameter, and the Header Name is Magicodes-Type as follows.

    public class AddRequiredHeaderParameter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<OpenApiParameter>();
            }

            operation.Parameters.Add(new OpenApiParameter
            {
                Name = "Magicodes-Type",
                In = ParameterLocation.Header,
                Required = false,
                Description = "根据HttpContentMediaType添加指定的header值,导出不同格式的文件。"
            });
        }
    }

Then go to the ConfigureServices() method and add the following to the AddSwaggerGen method.

   c.OperationFilter<AddRequiredHeaderParameter>();

XMLHttpRequest使用

XMLHttpRequest的使用中,和正常导出来说几乎一样,不过需要额外注意以下几个地方:

  • 修改responseType为blob。
  • 添加Http Header。
  • 以及对二进制流的处理。
document.querySelector("#downloadexcel").onclick = function() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "https://localhost:5001/api/Magicodes/excel", true); //也可以使用Post
    xmlhttp.responseType = 'blob';
    xmlhttp.setRequestHeader("Magicodes-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    xmlhttp.send();
    // readyState == 4 为请求完成,status == 200为请求成功返回的状态
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var name = xmlhttp.getResponseHeader("Content-disposition");
            var filename = name.substring(20, name.length);
            var blob = new Blob([xmlhttp.response], {
                type: 'text/xlsx'
            });
            var Url = URL.createObjectURL(blob);
            var link = document.createElement('a');
            link.href = Url;
            link.download = filename;
            link.click();
        }
    }
}

jQuery Ajax使用

对于jQuery AjaxXMLHttpRequest的注意事项是一致的。详细可参考如下代码示例,不过目前对于示例的演示只是针对于Excel导出的,关于其他格式的导出,可参考我们前面介绍的Magicodes-Type常量内容,当然对于其他文件的导出同样也是对responseType、以及blob类型进行修改。

$("#downloadexcel").click(function() {
    $.ajax({
        url: "https://localhost:5001/api/Magicodes/excel",
        type: 'GET',
        headers: {
            'Magicodes-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        },
        xhrFields: {
            responseType: 'blob'
        },
        success: function(data, status, xhr) {
            var name = xhr.getResponseHeader("Content-disposition");
            var filename = name.substring(20, name.length);
            var blob = new Blob([data], {
                type: 'text/xlsx'
            });
            var Url = URL.createObjectURL(blob);
            var link = document.createElement('a');
            link.href = Url;
            link.download = filename;
            link.click();
        }
    });
})

Reference

https://github.com/dotnetcore/Magicodes.IE